import urllib
import urllib2
import re

local = 0
servers = ("http://phoenix87.altervista.org/php5/dummychat/", "http://192.168.1.3/dummychat/")

server = servers[local]

timeout = 60

username = None

def _request(page, data):
    data = urllib.urlencode(data)
    try:
        req = urllib2.urlopen(server + page, data, timeout)
    except urllib2.URLError as err:
        return None, err.reason
        
    return req.read(), None

def login(username, password):
    return _request("login.php", [("submit", "client_req"), ("uname", username), ("pwd", password)])

def logout(username):
    return _request("logout.php", [("submit", "client_req"), ("uname", username)])

def get_user_uid(username):
    return _request("users.php", [("action","get_uid"),("uname", username)])

def get_contact_list(username):
    res, err = _request("users.php", [("action","get_user_list"),("uname", username)])
    if res == None: return None, err
    
    regex = re.compile("([^ ]+) ([0-9]) ([0-9.]+)\n")
    return regex.findall(res), None
    
def add_to_contact_list(username, contact):
    return _request("users.php", [("action","add_to_cl"),("uname", username),("contact",contact)])
